/*
 * Copyright 2012 ron-ang-code Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ron.ang.util.pdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import ron.ang.util.Data;

/*
 * This code requires the android.jar and itextpdf-5.3.2.jar
 * to compile, or you can convert this Java project to Android project.
 */
import android.content.ContentValues;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 
 * @author Ronillo Ang
 */
public class Document {

	private com.itextpdf.text.Document document;

	public Document(File output) throws IOException, DocumentException {
		this(output, PageSize.LEGAL);
	}

	public Document(File output, Rectangle pageSize) throws IOException,
			DocumentException {
		document = new com.itextpdf.text.Document(pageSize);
		PdfWriter.getInstance(document, new FileOutputStream(output));
		document.open();
	}

	public void addMetaData(String title, String subject, String keywords,
			String author, String creator) {
		document.addTitle(title);
		document.addSubject(subject);
		document.addKeywords(keywords);
		document.addAuthor(author);
		document.addCreator(creator);
	}

	public void add(Element element) throws DocumentException {
		document.add(element);
	}

	public boolean newPage() {
		return document.newPage();
	}

	public PdfPTable createTable(String[] headerColumn,
			List<? extends Data> dataList) {
		PdfPTable table = new PdfPTable(headerColumn.length);

		for (String column : headerColumn) {
			PdfPCell cell = new PdfPCell(new Phrase(column));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
		}

		table.setHeaderRows(1);

		for (Data dataObject : dataList) {
			ContentValues values = dataObject.toCSV();

			for (String key : headerColumn) {
				table.addCell(values.getAsString(key));
			}
		}

		return table;
	}

	public void close() {
		document.close();
	}
}
